package com.party.web.controller.tool;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.party.common.annotation.Log;
import com.party.common.core.controller.BaseController;
import com.party.common.core.domain.AjaxResult;
import com.party.common.enums.BusinessType;
import com.party.common.utils.StringUtils;
import com.party.common.utils.WxUtils;
import com.party.common.utils.http.HttpUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 企业微信工具接口
 * 
 */
@Api(tags = "企业微信工具接口")
@RestController
@RequestMapping("/tool/wework")
public class WeWorkController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(WeWorkController.class);
    
    // 用于缓存access_token的简单实现
    private static final Map<String, TokenInfo> tokenCache = new ConcurrentHashMap<>();
    private static final ReentrantLock lock = new ReentrantLock();
    // 企业微信配置信息（实际项目中应该从配置文件或数据库获取）
//    private static final String CORP_ID = "wwcd783e161afd66dd";
//    private static final String CORP_SECRET = "Q6fIwAb57xAPoRJjqWyrOLJg7AqmOiLzxZf-d3sDCnw";

    /**
     * 根据js_code获取企业微信会话信息
     */
    @ApiOperation("根据js_code获取企业微信会话信息")
    @PostMapping("/nologin/code2Session")
    @Log(title = "企业微信工具", businessType = BusinessType.OTHER)
    public AjaxResult getCodeSession(@RequestBody Map<String, Object> params) {
        String jsCode = (String) params.get("jsCode");
        if (StringUtils.isEmpty(jsCode)) {
            return AjaxResult.error("js_code不能为空");
        }

        // 获取企业微信应用的access_token
        String accessToken = WxUtils.getAccessToken();
        if (StringUtils.isEmpty(accessToken)) {
            return AjaxResult.error("获取企业微信access_token失败");
        }
        // 构造企业微信jscode2session接口URL
        String url = "https://qyapi.weixin.qq.com/cgi-bin/miniprogram/jscode2session?access_token=" + accessToken 
                    + "&js_code=" + jsCode + "&grant_type=authorization_code";
        
        try {
            // 发起GET请求调用企业微信API
            String response = HttpUtils.sendGet(url);
            JSONObject jsonResponse = JSON.parseObject(response);
            
            // 检查返回结果
            int errCode = jsonResponse.getIntValue("errcode");
            if (errCode != 0) {
                String errMsg = jsonResponse.getString("errmsg");
                log.error("企业微信code2Session接口调用失败，errcode: {}, errmsg: {}", errCode, errMsg);
                return AjaxResult.error("调用企业微信接口失败: " + errMsg);
            }
            
            log.info("企业微信code2Session接口调用成功，js_code: {}", jsCode);
            return AjaxResult.success(jsonResponse);
        } catch (Exception e) {
            log.error("企业微信code2Session接口调用失败，js_code: {}", jsCode, e);
            return AjaxResult.error("调用企业微信接口失败: " + e.getMessage());
        }
    }

    /**
     * 获取企业微信应用的access_token
     * 实现企业微信获取access_token接口：
     * https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ID&corpsecret=SECRET
     * @return access_token
     */
//    private String getAccessToken() {
//        // 检查缓存中是否已有有效的access_token
//        TokenInfo tokenInfo = tokenCache.get("default_app");
//        if (tokenInfo != null && !tokenInfo.isExpired()) {
//            return tokenInfo.getAccessToken();
//        }
//
//        // 双重检查锁，避免并发请求重复获取token
//        lock.lock();
//        try {
//            // 再次检查缓存，防止并发情况下重复获取
//            tokenInfo = tokenCache.get("default_app");
//            if (tokenInfo != null && !tokenInfo.isExpired()) {
//                return tokenInfo.getAccessToken();
//            }
//
//            // 调用企业微信获取access_token接口
//            String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + CORP_ID
//                        + "&corpsecret=" + CORP_SECRET;
//
//            try {
//                String response = HttpUtils.sendGet(url);
//                JSONObject jsonResponse = JSON.parseObject(response);
//
//                int errCode = jsonResponse.getIntValue("errcode");
//                if (errCode != 0) {
//                    String errMsg = jsonResponse.getString("errmsg");
//                    log.error("获取企业微信access_token失败，errcode: {}, errmsg: {}", errCode, errMsg);
//                    return null;
//                }
//
//                String accessToken = jsonResponse.getString("access_token");
//                int expiresIn = jsonResponse.getIntValue("expires_in");
//
//                // 缓存token信息（提前5分钟过期，避免边界问题）
//                TokenInfo newTokenInfo = new TokenInfo(accessToken, System.currentTimeMillis() + (expiresIn - 300) * 1000L);
//                tokenCache.put("default_app", newTokenInfo);
//
//                log.info("成功获取企业微信access_token，有效期{}秒", expiresIn);
//                return accessToken;
//            } catch (Exception e) {
//                log.error("获取企业微信access_token异常", e);
//                return null;
//            }
//        } finally {
//            lock.unlock();
//        }
//    }

    /**
     * 企业微信选择文件接口
     */
    @ApiOperation("企业微信选择文件接口")
    @PostMapping("/chooseMessageFile")
    @Log(title = "企业微信工具", businessType = BusinessType.OTHER)
    public AjaxResult chooseMessageFile(@RequestBody Map<String, Object> params) {
        Integer count = (Integer) params.get("count");
        String type = (String) params.get("type");
        
        if (count == null || count <= 0 || count > 100) {
            return AjaxResult.error("count参数错误，取值范围1-100");
        }
        
        // 模拟返回结果，实际应调用企业微信API
        Map<String, Object> result = new HashMap<>();
        result.put("errMsg", "chooseMessageFile:ok");
        
        // 模拟文件列表
        Map<String, Object> file1 = new HashMap<>();
        file1.put("localId", "localId1");
        file1.put("size", 1024);
        file1.put("name", "文件1.docx");
        file1.put("type", "file");
        file1.put("time", System.currentTimeMillis()/1000);
        
        Map<String, Object> file2 = new HashMap<>();
        file2.put("localId", "localId2");
        file2.put("size", 2048);
        file2.put("name", "图片1.jpg");
        file2.put("type", "image");
        file2.put("time", System.currentTimeMillis()/1000);
        
        Map<String, Object>[] tempFiles = new Map[]{file1, file2};
        result.put("tempFiles", tempFiles);
        
        log.info("企业微信选择文件接口调用成功，count: {}, type: {}", count, type);
        return AjaxResult.success(result);
    }

    /**
     * 获取本地文件数据
     */
    @ApiOperation("获取本地文件数据")
    @GetMapping("/getLocalFileData/{localId}")
    @Log(title = "企业微信工具", businessType = BusinessType.OTHER)
    public AjaxResult getLocalFileData(@PathVariable String localId) {
        if (StringUtils.isEmpty(localId)) {
            return AjaxResult.error("localId不能为空");
        }
        
        // 模拟返回结果，实际应根据localId获取文件数据
        Map<String, Object> result = new HashMap<>();
        result.put("errMsg", "getLocalFileData:ok");
        result.put("localData", "BASE64_ENCODED_FILE_DATA");
        result.put("size", 1024);
        
        log.info("企业微信获取本地文件数据接口调用成功，localId: {}", localId);
        return AjaxResult.success(result);
    }
    
    /**
     * 用于缓存access_token的信息类
     */
    private static class TokenInfo {
        private final String accessToken;
        private final long expireTime;
        
        public TokenInfo(String accessToken, long expireTime) {
            this.accessToken = accessToken;
            this.expireTime = expireTime;
        }
        
        public String getAccessToken() {
            return accessToken;
        }
        
        public boolean isExpired() {
            return System.currentTimeMillis() > expireTime;
        }
    }
}